//引入express
const express = require('express');
const fs = require('fs');
const app = express();
const cors = require('cors');
app.use(cors());
app.use('/asset',express.static('asset'));

//引入multer
const multer = require('multer');
//指定文件存储位置
const upload = multer({dest: './asset'});
//监听文件上传
app.post("/api/upload", upload.single('file'), (req, res) => {
    //文件对象信息
    let file = req.file;
    //这里修改文件名字，比较随意
    let tempPath = './asset/' + file.filename;
    let picName = getName(file.originalname);
    let picPath = './asset/' + picName;
    fs.renameSync(tempPath, picPath);
    res.send({
        msg:"上传成功！",
        data:'http://localhost/asset/' + picName
    });
})
//启动服务器，并监听80端口
app.listen(80,()=>{
    console.log("sever ok!");
})


function getName(name){
    let arr = name.split(".");
    let r = Date.now();
    return `${arr[0]}-${r}.${arr[1]}`;
}